package mrHunter.data;

import mrHunter.ProblemInf;
import mrHunter.ProblemList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class JdbcProblemRepository implements ProblemRepository{
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public JdbcProblemRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    @Override
    public ProblemList loadProblems() {
        //int problemNum=jdbcTemplate.queryForObject("select count(*) from probleminf ",Integer.TYPE);
        List<ProblemInf> problemInfs=new ArrayList<>();

        List<Map<String,Object>> rows=jdbcTemplate.queryForList("select * from probleminf");

        for (Map row:rows){
            ProblemInf problemInf=new ProblemInf();
            problemInf.setName((String)(row.get("name")));
            problemInf.setNo((int) (row.get("no")));
            problemInf.setDiff((String) (row.get("difficulty")));
            problemInf.setType((String)(row.get("type")));
            problemInf.setSubmit((int)(row.get("submit")));
            problemInfs.add(problemInf);
        }

        return new ProblemList(problemInfs);
    }

    @Override
    public ProblemInf getProblemInf(int no, String type) {
        return jdbcTemplate.queryForObject("select * from probleminf where type=? AND no=?", new JdbcProblemRepository.ProblemRowMapper(),type, no);
    }

    @Override
    public void updateSubmit(int no) {
        String sql="update probleminf set submit=submit+1 where no="+no;
        jdbcTemplate.execute(sql);
    }

    private static class ProblemRowMapper implements RowMapper<ProblemInf> {
        public ProblemInf mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new ProblemInf(
                    rs.getInt("no"),
                    rs.getString("name"),
                    rs.getString("difficulty"),
                    rs.getString("inputType"),
                    rs.getString("outputType"),
                    rs.getString("inputs"),
                    rs.getString("outputs"),
                    rs.getString("type"),
                    rs.getInt("inputNum"),
                    rs.getInt("outputNum"),
                    rs.getString("inputInf"),
                    rs.getString("outputInf"),
                    rs.getInt("submit"));
        }
    }

}
